/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 25228
 * Date: 2024-08-11
 * Time: 12:16
 */
class Solution2 {
    public int postindex=0;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        postindex=postorder.length-1;

        return buildTree2(postorder.length-1,0,inorder,postorder);
    }
    public TreeNode buildTree2(int end,int begin, int[] inorder, int[] postorder){
        if(begin>end){
            return null;
        }
        TreeNode root=new TreeNode(postorder[postindex]);

        int index=find(begin,end,postorder[postindex],inorder);
        postindex--;

        root.right=buildTree2(end,index+1,inorder, postorder);

        root.left=buildTree2(index-1,begin,inorder, postorder);

        return root;
    }
    public int find(int begin,int end,int x,int[] inorder){
        for(int i=begin;i<=end;i++){
            if(inorder[i]==x){
                return i;
            }
        }
        return -1;
    }
}
